﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using SPUtilities.ManageGroupsPerUser;

namespace SPUtilities.ManageGroupsPerUser.Layouts.SPUtilities.ManageGroupsPerUser
{
    public partial class ManageGroups : LayoutsPageBase
    {
        string userName;
        protected void Page_Load(object sender, EventArgs e)
        {
            lblProjectName.Text = SPContext.Current.Site.RootWeb.Title;
            lblProjectUrl.Text = SPContext.Current.Site.Url;

        }

        void FillAvaiableGroups()
        {

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite rootSite = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb rootWeb = rootSite.OpenWeb())
                    {
                        //rootWeb.
                        foreach (SPGroup spg in rootWeb.SiteGroups)//SITE GROUPS lista todos inclusive não associados à permissão nenhuma
                        {
                            lsbRemainingGroups.Items.Add(spg.Name);
                        }
                    }
                }
            });

            //}
        }

        void FillGroups(string UserName)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite rootSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb rootWeb = rootSite.OpenWeb())
                        {
                            //rootWeb.
                            foreach (SPGroup spg in rootWeb.SiteGroups)//SITE GROUPS lista todos inclusive não associados à permissão nenhuma
                            {
                                if (rootWeb.CheckIfGroupContainsUser(spg.Name, UserName))
                                {
                                    lsbCurrentGroups.Items.Add(spg.Name);
                                }
                                else if (rootWeb.CheckIfGroupContainsUser(spg.Name, UserName.GetLoginWithoutClaims()))
                                {
                                    lsbCurrentGroups.Items.Add(spg.Name);
                                }
                                else if (rootWeb.CheckIfGroupContainsUser(spg.Name, UserName.GetLoginWithClaims()))
                                {
                                    lsbCurrentGroups.Items.Add(spg.Name);

                                }
                                else
                                {
                                    lsbRemainingGroups.Items.Add(spg.Name);
                                }
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }

            //}
        }


        protected void btnLoadGroups_Click(object sender, EventArgs e)
        {
            try
            {
                lblCopiyng.Text = "";
                PickerEntity pe = (PickerEntity)userPicker.Entities[0];  //gets first user in list
                userName = pe.Key;
                if (userName.Contains("|"))
                {
                    lblUserName.Text = lblUserName2.Text = userName.GetLoginWithoutClaims();
                }
                else
                {
                    lblUserName.Text = lblUserName2.Text = userName;
                }

                lsbCurrentGroups.Items.Clear();
                lsbRemainingGroups.Items.Clear();

                FillGroups(userName);
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }
        }

        protected void btnDown_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            List<ListItem> itemsToMove = new List<ListItem>();

            //Vê quais estão selecionados na listbox de grupos disponíveis 
            foreach (ListItem li in lsbRemainingGroups.Items)
            {
                if (li.Selected)
                {
                    itemsToMove.Add(li);//Salva numa lista para posteriormente pegar o array. Deleta de uma vez dá erro no foreach
                }
            }
            //Array com cópia dos items à jogar na listbox de grupos associados
            var arrayToMove = itemsToMove.ToArray();
            //Adiciona aos grupos associados
            lsbCurrentGroups.Items.AddRange(arrayToMove);
            //Remove da lista original
            foreach (var li in arrayToMove)
            {
                lsbRemainingGroups.Items.Remove(li);
            }

            System.Collections.SortedList sorted = new System.Collections.SortedList();
            foreach (ListItem li in lsbCurrentGroups.Items)
            {
                sorted.Add(li.Text, li.Value);
            }
            lsbCurrentGroups.Items.Clear();
            foreach (String key in sorted.Keys)
            {
                lsbCurrentGroups.Items.Add(new ListItem(key, sorted[key].ToString()));
            }

        }

        protected void btnUp_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            List<ListItem> itemsToMove = new List<ListItem>();

            //Vê quais estão selecionados na listbox de grupos associados 
            foreach (ListItem li in lsbCurrentGroups.Items)
            {
                if (li.Selected)
                {
                    itemsToMove.Add(li);//Salva numa lista para posteriormente pegar o array. Deleta de uma vez dá erro no foreach
                }
            }
            //Array com cópia dos items à jogar na listbox de grupos disponíveis
            var arrayToMove = itemsToMove.ToArray();
            //Adiciona aos grupos disponíveis
            lsbRemainingGroups.Items.AddRange(arrayToMove);
            //Remove da lista original
            foreach (var li in arrayToMove)
            {
                lsbCurrentGroups.Items.Remove(li);
            }

            System.Collections.SortedList sorted = new System.Collections.SortedList();
            foreach (ListItem li in lsbRemainingGroups.Items)
            {
                sorted.Add(li.Text, li.Value);
            }
            lsbRemainingGroups.Items.Clear();
            foreach (String key in sorted.Keys)
            {
                lsbRemainingGroups.Items.Add(new ListItem(key, sorted[key].ToString()));
            }
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                PickerEntity pe = (PickerEntity)userPicker.Entities[0];  //gets first user in list
                userName = pe.Description;



                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite rootSite = new SPSite(SPContext.Current.Site.ID))
                    {
                        using (SPWeb rootWeb = rootSite.OpenWeb())
                        {
                            bool allowUnsafe = rootWeb.AllowUnsafeUpdates;
                            rootWeb.AllowUnsafeUpdates = true;
                            foreach (ListItem li in lsbRemainingGroups.Items)
                            {
                                if (rootWeb.CheckIfGroupContainsUser(li.Text, userName))
                                {
                                    SPUser user = rootWeb.EnsureUser(userName);
                                    rootWeb.SiteGroups[li.Text].RemoveUser(user);
                                }
                            }
                            foreach (ListItem li in lsbCurrentGroups.Items)
                            {
                                if (!rootWeb.CheckIfGroupContainsUser(li.Text, userName))
                                {
                                    SPUser user = rootWeb.EnsureUser(userName);
                                    rootWeb.SiteGroups[li.Text].AddUser(user);
                                }
                            }
                            rootWeb.AllowUnsafeUpdates = allowUnsafe;

                            ////rootWeb.
                            //foreach (SPGroup spg in rootWeb.SiteGroups)//SITE GROUPS lista todos inclusive não associados à permissão nenhuma
                            ////{
                            //    if (rootWeb.CheckIfGroupContainsUser(spg.Name, UserName))
                            //    {
                            //        lsbCurrentGroups.Items.Add(spg.Name);
                            //    }
                            //    else
                            //    {
                            //        lsbRemainingGroups.Items.Add(spg.Name);
                            //    }
                            //}
                            lblMessage.Text = "Sucessfully updated groups!";
                            //ClientScript.RegisterStartupScript(this.GetType(), "messageOk", "alert('Grupos atualizados com sucesso.')");
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                lblMessage.Text = ex.Message;
            }

        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {
            chkCopy.Checked = false;
            chkCopy_CheckedChanged(sender, e);
            btnLoadGroups_Click(sender, e);
        }


        protected void btnCopiarPermissoes_Click(object sender, EventArgs e)
        {
            PickerEntity pe = (PickerEntity)userPickerToCopy.Entities[0];  //gets first user in list
            lblCopiyng.Text = "Copiando permissões de: " + pe.Description;
            lsbCurrentGroups.Items.Clear();
            lsbRemainingGroups.Items.Clear();

            FillGroups(pe.Description);
        }

        protected void chkCopy_CheckedChanged(object sender, EventArgs e)
        {
            userPickerToCopy.AllowEmpty = btnDown.Enabled = btnUp.Enabled = btnUp.Visible = btnDown.Visible = !chkCopy.Checked;
            trCloneUserGroups.Visible = chkCopy.Checked;

            if (!chkCopy.Checked)
            {
                btnLoadGroups_Click(sender, e);
            }
        }


    }
}
